/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 jfinal app. jfapp Group.
 */

package app.models.game;

import com.github.sog.annotation.TableBind;
import com.github.sog.config.StringPool;
import com.github.sog.controller.datatables.core.ColumnDef;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * The table ol_game mapping model.
 * </p>
 */
@TableBind(tableName = "ol_game")
public class Game extends Model<Game> {

    private static final long   serialVersionUID = 1L;
    /**
     * The public dao.
     */
    public static final Game dao = new Game();


    public List<Game> list(){
    	return find(SqlKit.sql("game.list"));
    }

    public Page<Game> datatable(DatatablesCriterias criterias) {
        int pageSize = criterias.getDisplaySize();
        int start = criterias.getDisplayStart() / pageSize + 1;
        final List<ColumnDef> sortingColumnDefs = criterias.getSortingColumnDefs();
        String where = " FROM ol_game, ol_game_category,ol_game_rule " +
                " WHERE ol_game.category=ol_game_category.id" +
                " AND ol_game.game_rule=ol_game_rule.id";
        if (sortingColumnDefs != null && !sortingColumnDefs.isEmpty()) {
            StringBuilder orderBy = new StringBuilder();
            for (ColumnDef sortingColumnDef : sortingColumnDefs)
                if (sortingColumnDef.isSortable()) {
                    orderBy.append(sortingColumnDef.getName()).append(StringPool.SPACE).append(sortingColumnDef.getSortDirection().toString());
                }
            // todo mulite column.
            final String byColumns = orderBy.toString();
            if(!Strings.isNullOrEmpty(byColumns)){
                where += " ORDER BY " + byColumns;
            }
        }
        if (!where.contains("ORDER")) {
            where += " ORDER BY id DESC";
        }

        return paginate(start, pageSize, SqlKit.sql("game.columns"), where);
    }

    public List<Game> gameList() {
        Date now = new Date();
        //String now = "2014-04-22 23:29:00";
        return find(SqlKit.sql("game.gameList"), now, now);
    }
}